const express = require('express')
const router = express.Router()
const models = require('../models')
const Result = require('../utils/Result')

router.get('/test', async (req, res) => {
    res.send('ok....')
})


/**
 *  @Router post /tags/addTag
 *  @desc 新增标签
 *  @access 接口是私有的
 */
router.post('/set', async(req, res) => {
    const { tagName, bgColor,textColor,fontSize } = req.body
    const data = { tagName, bgColor,textColor,fontSize }
    const bool = await models.Tag.count({where:{tagName}})
    if(bool){
        const result = await models.Tag.update(data,{where:{tagName}})
        return new Result(result,`修改标签成功`).success(res)
    }else{
        const result = await models.Tag.create(data)
        return new Result(result,`新增标签成功`).success(res)
    }
})

router.get('/query', async function (req, res, next) {
    let currentPage = parseInt(req.query.currentPage) || 1
    let pageSize = parseInt(req.query.pageSize) || 5
    let where = {};
    let result = await models.Tag.findAndCountAll({
        order: [['id', 'DESC']], //倒叙的方式输出 对比id 默认为ASC正序
        where,   //模糊查询的条件
        offset: (currentPage - 1) * pageSize,
        limit: pageSize,
        raw: true,
    })
    new Result(result, '获取成功').success(res)
});

router.get('/article', async function (req, res, next) {
    let currentPage = parseInt(req.query.currentPage) || 1
    let pageSize = parseInt(req.query.pageSize) || 5
    const {tagId} = req.query
    let where = {tagId};
    let result = await models.Article.findAndCountAll({
        order: [['id', 'DESC']], //倒叙的方式输出 对比id 默认为ASC正序
        where,   //模糊查询的条件
        offset: (currentPage - 1) * pageSize,
        limit: pageSize,
        raw: true,
        include: [
            { model: models.Type, attributes: ['className'] },
            { model: models.User, attributes: ['nickname'] },
            { model: models.Tag, attributes: ['tagName'] }
        ]
    })
    new Result(result, '获取成功').success(res)
});

router.post('/del', async(req, res) => {
    const {id} = req.body
    const bool = await models.Article.count({where:{tagId:id}})
    if(bool){
      return new Result(null,'有文章正在使用中，不可删除此标签').fail(res)
    }else{
        const result = await models.Tag.destroy({where:{id}})
        new Result(result,`删除成功`).success(res)
    }
})

// router.get('/query', async(req, res) => {
//     const result = await models.Tag.findAll()
//     new Result(result,`获取标签成功`).success(res)
// })



module.exports = router